package com.yryp.sign.web.controller;


import com.alibaba.fastjson.JSON;
import com.yryp.sign.common.Result;
import com.yryp.sign.common.ResultGenerator;
import com.yryp.sign.entry.SignPerson;
import com.yryp.sign.mq.Sender;
import com.yryp.sign.utils.DateTimeUtil;
import com.yryp.sign.web.service.SignService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sign")
public class SignController {

    Logger logger = LoggerFactory.getLogger(SignController.class);

    @Autowired
    private Sender sender;

    @Autowired
    private SignService signService;


    /**
     * @param invitationCode 接待号（人员唯一码）
     * @param name 代领人姓名（如果是本人领取，此字段为空）
     * @param md5Number 证件号（md5加密的证件号）
     * @param oneself 是否本人领取（1：是，0：否）
     * @param documentNumber 代领人身份证号（如果是本人领取，此字段为空）
     * @param documentNumberReal 签到人身份证号码，当系统没有录入签到人身份证时推送
     * @return findNot未找到,signed已签到,success签到成功,pushFail推送失败
     */
    @ResponseBody
    @PostMapping("/sign")
    public Result<String> sign(String invitationCode,
                               String name,
                               String oneself,
                               String md5Number,
                               String documentNumber,
                               String documentNumberReal){
        SignPerson signPerson = null;
        if (StringUtils.isEmpty(invitationCode)){
            signPerson = signService.selectByMd5Number(md5Number);
            if (null == signPerson){
                return ResultGenerator.genSuccessResult("findNot");
            }
            invitationCode = signPerson.getInvitationCode();
        }else {
            signPerson = signService.selectById(invitationCode);
        }
        if (StringUtils.isNotEmpty(signPerson.getSignTime())){
            return ResultGenerator.genSuccessResult("signed");
        }
        //签到时间
        String signTime = DateTimeUtil.getFormatCurrentTime();

        Map<String, String> sendDataMap = new HashMap<>();
        sendDataMap.put("invitationCode", invitationCode);
        sendDataMap.put("name",name);
        sendDataMap.put("oneself",oneself);
        sendDataMap.put("documentNumber",documentNumber);
        sendDataMap.put("signTime", signTime);
        sendDataMap.put("documentNumberReal", documentNumberReal);
        signPerson.setSignTime(signTime);

        try {
            sender.send(JSON.toJSONString(sendDataMap));
            signService.updateSignPerson(signPerson);
            return ResultGenerator.genSuccessResult("success");
        } catch (Exception e) {
            logger.error("推送签到信息到MQ失败",e);
            return ResultGenerator.genSuccessResult("pushFail");
        }
    }

    /**
     * 代签时通过名字获取系统内的信息
     * @param name 代签人输入的名字
     * @return
     */
    @ResponseBody
    @GetMapping("/dataByName")
    public Result<List<SignPerson>> dataByName(String name){
        List<SignPerson> list = signService.selectByName(name);
        if (list == null) list = new ArrayList<>();
        return ResultGenerator.genSuccessResult(list);
    }

    /**
     * 获取签到的信息展示在识别页面
     * @param md5Number 证件号（md5加密的证件号）
     * @return
     */
    @ResponseBody
    @GetMapping("/dataByCardNumber")
    public Result<SignPerson> dataByCardNumber(String md5Number){
        return ResultGenerator.genSuccessResult(signService.selectByMd5Number(md5Number));
    }

    /**
     *
     * @param md5Number
     * @param name
     * @return msg : md5 , no , name 通过何种方式查找到的
     */
    @ResponseBody
    @GetMapping("/signInfo")
    public Result<List<SignPerson>> signInfo(String md5Number, String name) {

        Result<List<SignPerson>> result =  ResultGenerator.genSuccessResult();
        SignPerson sp = signService.selectByMd5Number(md5Number);
        if (sp!=null){
            List<SignPerson> list = new ArrayList<>();
            list.add(sp);
            result.setMessage("md5");
            result.setData(list);
            return result;
        }else {
            List<SignPerson> list = signService.selectByName(name);
            if (null == list || list.isEmpty()){
                result.setMessage("no");
            }else {
                List<SignPerson> newList = new ArrayList<>();
                //选择无身份证号的数据
                list.forEach(signPerson -> {
                    if (StringUtils.isEmpty(signPerson.getDocumentNumber())){
                        newList.add(signPerson);
                    }
                });
                result.setMessage("name");
                result.setData(newList);
            }
            return result;
        }

    }
}
